'use client';

import { useState } from 'react';
import { searchDocForCoze } from '@/utils/coze';
import './index.scss';
import classNames from 'classnames';

export default function Index() {
  const [isShow, setIsShow] = useState(true);
  const [searchValue, setSearchValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [contentList, setContentList] = useState([
    {
      type: 'AI',
      content:
        '你好，欢迎来到章津诚的个人网站，我可以帮助你查找网站中的内容哦！',
    },
  ]);

  const searchForCoze = async (question: string) => {
    setIsLoading(true);
    setSearchValue('');
    setContentList((preValue) => [
      ...preValue,
      {
        type: 'user',
        content: question,
      },
      {
        type: 'AI',
        content: '',
      },
    ]);

    const stream = searchDocForCoze(question);

    for await (const event of stream) {
      if (event.event === 'Done') {
        setIsLoading(false);
        break;
      }
      const data: any = event.data;
      if (data) {
        const str = data.content;
        setContentList((preValue) => {
          const lastItem = JSON.parse(
            JSON.stringify(preValue[preValue.length - 1])
          );
          lastItem.content = lastItem.content + str;
          return [...preValue.slice(0, preValue.length - 1), lastItem];
        });
      }
    }
  };

  return (
    <div
      className={classNames('search-coze', { 'search-coze-hidden': !isShow })}
    >
      <div className="mask">
        <div className="screen-box">
          {contentList.map((item, index) => {
            if (item.type === 'AI') {
              return (
                <div className="chatting chatting-ai" key={index}>
                  <div className="content">{item.content}</div>
                </div>
              );
            } else {
              return (
                <div className="chatting chatting-user" key={index}>
                  <div className="content">{item.content}</div>
                </div>
              );
            }
          })}
        </div>
        <div className="input-box">
          <textarea
            placeholder="请输入你想搜索的内容"
            value={searchValue}
            disabled={isLoading}
            onChange={(e) => {
              setSearchValue(e.target.value);
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                if (searchValue.trim()) searchForCoze(searchValue);
              }
            }}
          />
        </div>
        <button className="button-close" onClick={() => setIsShow(false)}>
          <span className="x"></span>
          <span className="y"></span>
        </button>
      </div>
    </div>
  );
}
